/**
 * 
 */
package com.beforesunrise.project.server.mapservice.impl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import com.beforesunrise.project.server.mapservice.GeocodingService;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.google.appengine.repackaged.org.json.JSONTokener;

/**
 * @author ygkim
 *
 */
public class GeocodingServiceImpl implements GeocodingService {

	/* (non-Javadoc)
	 * @see com.beforesunrise.project.server.mapservice.GeocodingService#getGeometry(java.lang.String)
	 */
	@Override
	public String getGeometry(String keyword) {
		
		URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService();
		String resultString = null;
		
		try {
			
			StringBuffer urlStBuffer = new StringBuffer();
			
			urlStBuffer.append("http://maps.google.com/maps/api/geocode/json?address=");
			urlStBuffer.append(keyword);
			urlStBuffer.append("&sensor=false");
						
			URL url = new URL(urlStBuffer.toString());
			
			HTTPResponse response = urlFetchService.fetch(url);
			
			byte[] result = response.getContent();
			
			String jsonString = new String(result);
			
			JSONTokener jsonTokener = new JSONTokener(jsonString);
			
			System.out.println(jsonTokener.toString());
			
			if (jsonTokener.more()) {
				try {
					JSONObject jsonObj = (JSONObject) jsonTokener.nextValue();
					JSONArray jsonResults = jsonObj.getJSONArray("results");
					JSONObject jsonGeometry = null;
					if(jsonResults != null && jsonResults.length() > 0) {
						jsonGeometry = (JSONObject)jsonResults.get(0);
						JSONObject geoInfo = jsonGeometry.getJSONObject("geometry");
						JSONObject locationInfo = geoInfo.getJSONObject("location");
						double lng = locationInfo.getDouble("lng");
						double lat = locationInfo.getDouble("lat");
						resultString = String.format("%f,%f", lng, lat);
//						jsonGeometry.get
					}
//					JSONObject jsonGeometry = jsonResults.
					//resultString = jsonResults.toString();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}		
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return resultString;
	}

}
